from django.conf import settings
from celery import shared_task
from PIL import Image


@shared_task
def Photoshop_Touch(filetype, filename):
    """处理图片"""
    filename = filename.split("/")[-1]
    if filetype == "face":
        size = (128, 128)
        box = (0, 0, 128, 128)
    else:
        size = (512, 1024)
        box = (0, 0, 512, 1024)
    gap = 3.0
    rsp = Image.BICUBIC
    # Image.BICUBIC 双立方插值| Image.BILINEAR 双线性插值| Image.LANCZOS 下采样过滤插值| Image.NEAREST 最近邻插值
    try:
        # 加载文件
        im = Image.open(settings.MEDIA_ROOT / filename)
        # 对象属性
        # print(im.size)
        # print(im.format)
        # print(im.mode)
        si = im.size

        # 计算倍率
        bi = 1
        if si[0] > si[1] and si[1] > size[1]:
            bi = size[1] / si[1]
        if si[0] < si[1] and si[0] > size[0]:
            bi = size[0] / si[0]

        # 区域缩放
        # im_new = im.resize(
        #     (int(si[0] * bi), int(si[1] * bi)), resample=rsp, box=box, reducing_gap=gap
        # )
        # im_new.save(settings.MEDIA_ROOT / filename)

        # 全图缩放
        im.thumbnail((int(si[0] * bi), int(si[1] * bi)), rsp)

        # 裁剪并保存
        im.crop(box).save(settings.MEDIA_ROOT / filename)
    except IOError:
        return False
    else:
        return True
